package com.koron.css2.newProjectCenter.callback;

import com.alibaba.fastjson.JSONObject;
import com.koron.css2.baseConfig.mapper.ConfigMapper;
import com.koron.css2.clientCenter.bean.UserBean;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.newProjectCenter.bean.PjCollection;
import com.koron.css2.newProjectCenter.bean.PjInfoBean;
import com.koron.css2.newProjectCenter.bean.PjMeter;
import com.koron.css2.newProjectCenter.bean.query.PjCollectionQuery;
import com.koron.css2.newProjectCenter.mapper.PjCollectionMapper;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.newProjectCenter.mapper.PjMeterMapper;
import com.koron.css2.newProjectCenter.service.PjInfoService;
import com.koron.css2.newProjectCenter.vo.gcjs.GJResponseData;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.HttpUtil;
import com.koron.util.secret.StaticInfo;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.koron.css2.newProjectCenter.service.gcjsData.ZjAcceptanceInfo;

/**
 * 安装施工节点回调
 */
@Service(PjInfoService.INSTALL_BUILD)
public class InstallBuildCallback implements IPjInfoNodeCallback{

    private static Logger logger = LoggerFactory.getLogger(InstallBuildCallback.class);

    // 施工安装节点表身码是否必填 0 不必填 1 必填
    private static final String INSTALL_BUILD_FACTORY_NO_MUST_VALUE = "1";

    // 水表扩缩
    private static final String PJ_TYPE_3 = "3";

    @Override
    public MessageBean callback(SessionFactory factory, PjInfoBean pjInfoBean, UserInfoBean userInfo) {
        PjMeterMapper pjMeterMapper = factory.getMapper(PjMeterMapper.class);
        PjInfoMapper pjInfoMapper = factory.getMapper(PjInfoMapper.class);
        ConfigMapper configMapper = factory.getMapper(ConfigMapper.class);
        UserInfoMapper userInfoMapper = factory.getMapper(UserInfoMapper.class);
        // 施工安装节点表身码是否必填配置项
        String INSTALL_BUILD_FACTORY_NO_MUST = configMapper.getConfigValueByName("INSTALL_BUILD_FACTORY_NO_MUST");
        if (Objects.equals(INSTALL_BUILD_FACTORY_NO_MUST_VALUE, INSTALL_BUILD_FACTORY_NO_MUST)){
            List<PjMeter> pjMeterList = pjMeterMapper.getListByConsultId(pjInfoBean.getId());
            // 表身码必填校验
            for (int i = 0; i < pjMeterList.size(); i++){
                if(StringUtils.isEmpty(pjMeterList.get(i).getMsInfoId())){
                    return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表信息中第" + (i + 1) + "行的表身码未填写,请填写完保存后再进行提交", String.class);
                }
            }
            // 如果是水表扩缩，则进行旧表底码必填校验
            if (Objects.equals(PJ_TYPE_3, pjInfoBean.getPjType())){
                // 将临时表用户信息ID 转成集合
                List<String> userInfoIdList = pjMeterList.stream().map(t -> t.getUserInfoTempId()).collect(Collectors.toList());
                // 获取用户信息
                List<UserBean> userList = userInfoMapper.selectListByIds(userInfoIdList, UserBean.USERTEMP);
                // 将用户集合转成Map
                Map<String, UserBean> userMap = userList.stream().collect(Collectors.toMap(UserBean::getId, Function.identity()));
                for (int i = 0; i < pjMeterList.size(); i++){
                    UserBean user = userMap.get(pjMeterList.get(i).getUserInfoTempId());
                    // 旧表底码校验
                    if (user != null && user.getOldLastReadingNum() == null){
                        return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表信息中第" + (i + 1) + "行的旧表底码未填写,请填写完保存后再进行提交", String.class);
                    }
                }
            }
        }

        PjCollectionMapper pjCollectionMapper = factory.getMapper(PjCollectionMapper.class);
        PjCollectionQuery pjCollectionQuery = new PjCollectionQuery();
        pjCollectionQuery.setProjectCode(pjInfoBean.getBillNo());
        List<PjCollection> pjCollections = pjCollectionMapper.getList(pjCollectionQuery);
        for (PjCollection pjCollection : pjCollections){
            if (pjCollection.getProcessState() == null || Arrays.asList("register", "processing", "collection").contains(pjCollection.getProcessState().toLowerCase())){
                return MessageBean.create(Constant.MESSAGE_INT_FAIL, "该工程还未收款，不能进行下一步", Void.class);
            }
        }
        /**
         * 施工通水后后将结束办结状态同步到工建系统
         */
        if  (GCJS_COMPANY.equals(userInfo.getCurWaterCode()) && pjInfoBean.getGcjsStatic() == 3) {
            //修改工建受理状态
            pjInfoMapper.updateGcjsStaticById(pjInfoBean.getId(), 4);
            try {
                JSONObject jsonObject = ZjAcceptanceInfo(null, "3", pjInfoBean, userInfo, factory);
                logger.info("报装审批数据推送至工建参数：" + jsonObject.toJSONString());
                String s = HttpUtil.sendPost(StaticInfo.interBusiApi + "/gcjs/statusUpdateReception", jsonObject.toJSONString());
                GJResponseData responseData = com.koron.util.JsonUtils.jsonToPojo(s, GJResponseData.class);
                if (responseData.getErrcode() != GJResponseData.SUCCESS_CODE) {
                    logger.error("审批推送办结状态至工建失败:"+ responseData.getMessage());
                }
            } catch (Exception e) {
                logger.error("审批推送办结状态至工建失败",e);
            }
        }
        return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", Void.class);
    }
}
